package com.srd.phone.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.shengrongdai.srd.R;
import com.srd.phone.activity.DialogVerificationActivity;
import com.srd.phone.activity.RegisterSuccessActivity;
import com.srd.phone.application.AppActivityManager;
import com.srd.phone.bean.ResultInfo;
import com.srd.phone.bean.UserInfo;
import com.srd.phone.mvp.presenters.RegistPeoplePresenter;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.PreferenceUtils;
import com.srd.phone.utils.UserUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人注册
 */
public class RegisterPeopleFragment extends BaseFragment implements View.OnClickListener {

    private RegistPeoplePresenter registPeoplePresenter = null;
    private String common_url = Constants.BASEURL + "loginapp/commonReg"; //普通用户注册
    private String third_url = Constants.BASEURL + "loginapp/ThirdReg"; //第三方注册
    private String phcode_url = Constants.BASEURL + "loginapp/phCode"; //手机验证码
    private String urlLogin = Constants.BASEURL + "loginapp/login"; //登陆
    private String urlValidUser = Constants.BASEURL + "bmarkApp/bmarkPersonBorrow"; //验证用户是否存在

    private View rootView;
    private EditText et_user;
    private EditText et_pwd;
    private EditText et_check;
    private EditText et_verify;
    private CheckBox cb_protocol;
    private TextView tv_protocol;
    private Button bt_register;
    private TextView tv_warn;
    private Button bt_sms;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_register_people, container, false);
            initView();
            initData();
        }
        return rootView;
    }

    @Override
    public void initView() {
        et_user = (EditText) rootView.findViewById(R.id.et_user);
        et_pwd = (EditText) rootView.findViewById(R.id.et_pwd);
        et_check = (EditText) rootView.findViewById(R.id.et_check_pwd);
        et_verify = (EditText) rootView.findViewById(R.id.et_verify);
        bt_register = (Button) rootView.findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);
        cb_protocol = (CheckBox) rootView.findViewById(R.id.cb_protocol);
        tv_protocol = (TextView) rootView.findViewById(R.id.tv_protocol);
        tv_warn = (TextView) rootView.findViewById(R.id.tv_warn);
        bt_sms = (Button) rootView.findViewById(R.id.bt_sms);
        bt_sms.setOnClickListener(this);
    }

    public void initData() {
        presenter = new RegistPeoplePresenter(requestQueue, this);
        registPeoplePresenter = (RegistPeoplePresenter) presenter;
        registPeoplePresenter.setProtocol(tv_protocol);
        setUrlArrs(common_url, third_url, phcode_url, urlLogin);
    }

    //验证用户是否存在
    public void checkValidUser() {
        String phone = et_user.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(mContext, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("input", phone);
        registPeoplePresenter.requestPostData(urlValidUser, map);
    }


    //注册
    private void registerSubmit() {
        String phone = et_user.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();
        String check_pwd = et_check.getText().toString().trim();
        String check_verify = et_verify.getText().toString().trim();
        boolean isArgree = cb_protocol.isChecked();
        String mRegister = registPeoplePresenter.checkRegister(phone, pwd, check_pwd, check_verify, isArgree);
        if (TextUtils.isEmpty(mRegister)) {
            mContext.showWaitingDialog();
            tv_warn.setVisibility(View.INVISIBLE);
            registPeoplePresenter.requestData(common_url, phone, pwd, "", phone, "", "4", check_verify);
        } else {
            tv_warn.setText(mRegister);
            tv_warn.setVisibility(View.VISIBLE);
        }
    }

    //发送短信验证码
    private void sendSMScode() {
        String phone = et_user.getText().toString().trim();
        String alert = null;
        if (TextUtils.isEmpty(phone)) {
            alert = "手机号码不能为空";
            tv_warn.setText(alert);
            tv_warn.setVisibility(View.VISIBLE);
        } else if (!registPeoplePresenter.checkPhone(phone)) {
            alert = "手机号码不存在";
            tv_warn.setText(alert);
            tv_warn.setVisibility(View.VISIBLE);
        } else {
            startActivityForResult(new Intent(mContext, DialogVerificationActivity.class), getActivity().RESULT_FIRST_USER);
        }
    }

    //登录
    private void loginSubmit() {
        String name = et_user.getText().toString();
        String pwd = et_pwd.getText().toString();
        registPeoplePresenter.requestLogin(urlLogin, name, pwd, "");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1000) { //验证码验证成功
            registPeoplePresenter.requestMSMCode(phcode_url, et_user.getText().toString().trim());
            tv_warn.setVisibility(View.INVISIBLE);
            downTimer.start();
            bt_sms.setEnabled(false);
        }
    }

    CountDownTimer downTimer = new CountDownTimer(1000 * 60, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            bt_sms.setText("剩余" + millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            bt_sms.setEnabled(true);
            bt_sms.setText("重新获取");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_sms:
                sendSMScode();
                break;
            case R.id.bt_register:
                checkValidUser();
                break;
        }
    }

    @Override
    public void returnData(String tag, String data) {
        ResultInfo info = ResultInfo.parse(data);
        if (tag.equals(common_url)) {//注册
            if (info.code == -101) {
                loginSubmit();
                return;
            }
            Toast.makeText(mContext, info.msg, Toast.LENGTH_SHORT).show();
        } else if (tag == urlLogin) { //登录返回值
            mContext.cancelWaitingDialog();
            UserInfo userinfo = UserInfo.parse(data);
            if (userinfo.code == -101) {
                PreferenceUtils.getInstance().putData(Constants.LOGIN_STATUS, true);
                userinfo.userName = et_user.getText().toString().trim();
                userinfo.pwd = et_pwd.getText().toString().trim();
                UserUtils.saveUserInfo(userinfo);
                AppActivityManager.getInstance().popActivity(); //退出当前的activity
                AppActivityManager.getInstance().popActivity(); //退出登录的activity
                mContext.gotoActivity(RegisterSuccessActivity.class);
                return;
            }
        } else if (tag == urlValidUser) { //验证用户是否存在
            if (info.code != 0) {
                Toast.makeText(mContext, "手机号码已注册过", Toast.LENGTH_SHORT).show();
            } else {
                registerSubmit();
            }
        }
    }

    @Override
    public void onError(String tag, VolleyError error) {
        super.onError(tag, error);
    }

    @Override
    public void onDestroy() {
        downTimer.cancel();
        super.onDestroy();
    }
}
